/**
 * 设备信息服务
 * 提供设备和应用信息的获取功能
 */

class DeviceInfoService {
  /**
   * 获取设备信息
   * @returns {Promise<Object>} 设备信息对象
   */
  static async getDeviceInfo() {
    try {
      // 使用同步方法获取系统信息
      const systemInfo = uni.getSystemInfoSync();
      
      const deviceInfo = {
        brand: systemInfo.brand || '未知',
        model: systemInfo.model || '未知',
        system: systemInfo.system || '未知',
        platform: systemInfo.platform || '未知',
        screenWidth: systemInfo.screenWidth || 0,
        screenHeight: systemInfo.screenHeight || 0,
        pixelRatio: systemInfo.pixelRatio || 1,
        language: systemInfo.language || '未知',
        version: systemInfo.version || '未知',
        SDKVersion: systemInfo.SDKVersion || '未知',
        windowWidth: systemInfo.windowWidth || 0,
        windowHeight: systemInfo.windowHeight || 0,
        statusBarHeight: systemInfo.statusBarHeight || 0,
        fontSizeSetting: systemInfo.fontSizeSetting || 0
      };
      
      // #ifdef APP-PLUS
      // APP平台获取额外信息
      if (typeof plus !== 'undefined' && plus.device) {
        deviceInfo.uuid = plus.device.uuid || '未知';
        deviceInfo.vendor = plus.device.vendor || '未知';
        deviceInfo.isSimulator = plus.device.isSimulator ? plus.device.isSimulator() : false;
        
        // 获取存储信息
        try {
          const storageInfo = await this.getStorageInfo();
          deviceInfo.storageInfo = storageInfo;
        } catch (error) {
          console.error('获取存储信息失败:', error);
          deviceInfo.storageInfo = null;
        }
      }
      // #endif
      
      return deviceInfo;
    } catch (error) {
      console.error('获取设备信息失败:', error);
      throw new Error('获取设备信息失败');
    }
  }
  
  /**
   * 获取应用信息
   * @returns {Object} 应用信息对象
   */
  static getAppInfo() {
    try {
      const appInfo = {
        version: '1.0.0',
        environment: 'production',
        platform: ''
      };
      
      // 从本地存储读取应用版本
      try {
        const savedVersion = uni.getStorageSync('app_version');
        if (savedVersion) {
          appInfo.version = savedVersion;
        }
      } catch (error) {
        console.log('读取应用版本失败:', error);
      }
      
      // 判断运行环境
      // #ifdef H5
      appInfo.platform = 'H5';
      if (typeof window !== 'undefined') {
        const hostname = window.location.hostname;
        if (hostname === 'localhost' || 
            hostname === '127.0.0.1' || 
            hostname.includes('192.168.')) {
          appInfo.environment = 'development';
        }
      }
      // #endif
      
      // #ifdef APP-PLUS
      appInfo.platform = 'APP-PLUS';
      if (typeof plus !== 'undefined' && plus.runtime) {
        // 尝试获取应用版本
        plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
          if (widgetInfo && widgetInfo.version) {
            appInfo.version = widgetInfo.version;
            // 保存到本地存储
            try {
              uni.setStorageSync('app_version', widgetInfo.version);
            } catch (error) {
              console.error('保存应用版本失败:', error);
            }
          }
        });
      }
      // #endif
      
      // #ifdef MP-WEIXIN
      appInfo.platform = '微信小程序';
      // #endif
      
      // #ifdef MP-ALIPAY
      appInfo.platform = '支付宝小程序';
      // #endif
      
      // #ifdef MP-BAIDU
      appInfo.platform = '百度小程序';
      // #endif
      
      return appInfo;
    } catch (error) {
      console.error('获取应用信息失败:', error);
      return {
        version: '未知',
        environment: '未知',
        platform: '未知'
      };
    }
  }
  
  /**
   * 获取存储信息（仅APP-PLUS平台）
   * @returns {Promise<Object>} 存储信息对象
   */
  static getStorageInfo() {
    return new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
      if (typeof plus !== 'undefined' && plus.storage) {
        try {
          plus.storage.getStorageInfo({
            success: (info) => {
              const storageInfo = {
                total: info.totalSize || 0,
                used: info.usedSize || 0,
                free: (info.totalSize || 0) - (info.usedSize || 0)
              };
              resolve(storageInfo);
            },
            fail: (error) => {
              console.error('获取存储信息失败:', error);
              reject(new Error('获取存储信息失败'));
            }
          });
        } catch (error) {
          console.error('获取存储信息异常:', error);
          reject(error);
        }
      } else {
        reject(new Error('当前平台不支持获取存储信息'));
      }
      // #endif
      
      // #ifndef APP-PLUS
      reject(new Error('当前平台不支持获取存储信息'));
      // #endif
    });
  }
  
  /**
   * 格式化字节大小
   * @param {number} bytes - 字节数
   * @returns {string} 格式化后的大小字符串
   */
  static formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    if (!Number.isFinite(bytes) || bytes < 0) return '未知';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
    
    const value = bytes / Math.pow(k, i);
    return `${value.toFixed(2)} ${sizes[i]}`;
  }
  
  /**
   * 获取完整的设备和应用信息
   * @returns {Promise<Object>} 包含设备和应用信息的对象
   */
  static async getAllInfo() {
    try {
      const deviceInfo = await this.getDeviceInfo();
      const appInfo = this.getAppInfo();
      
      return {
        device: deviceInfo,
        app: appInfo
      };
    } catch (error) {
      console.error('获取完整信息失败:', error);
      throw error;
    }
  }
}

export default DeviceInfoService;
